package cn.com.surker.material.service.impl;

import cn.com.surker.business.dao.BusinessLogDao;
import cn.com.surker.business.entity.BusinessLog;
import cn.com.surker.common.MessageCenterException;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.dto.main.MaterialWeightQueryDTO;
import cn.com.surker.enums.business.BusinessTypeEnum;
import cn.com.surker.enums.material.MaterialContractTypeEnum;
import cn.com.surker.enums.oa.ProcessMessageEnum;
import cn.com.surker.enums.system.DataBaseEnum;
import cn.com.surker.material.dao.MainMaterialWeightDao;
import cn.com.surker.material.entity.MainMaterialWeight;
import cn.com.surker.material.service.MaterialWeightBaseService;
import cn.com.surker.material.vo.MainMaterialWeightVo;
import cn.com.surker.platform.dao.PlatformUserDao;
import cn.com.surker.platform.entity.PlatformUser;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.dao.SysOriginDao;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.system.entity.SysOrigin;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.OrderNoUtil;
import cn.com.surker.util.StringUtils;
import cn.com.surker.vo.main.MainMaterialWeightVO;
import cn.com.surker.weight.entity.WeightPicture;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author lucky
 * @create 2024年10月09 9:15
 * @desc
 */
public abstract class MaterialWeightBaseServiceImpl implements MaterialWeightBaseService {

    @Resource
    protected MainMaterialWeightDao materialWeightDao;
    @Resource
    protected SysOriginDao originDao;
    @Resource
    protected PlatformUserDao platformUserDao;
    @Resource
    protected DataSourceInfoDao dsDao;
    @Resource
    protected BusinessLogDao businessLogDao;

    /**
     * 分页查询过磅信息
//     * @param searchVal 检索条件
//     * @param orgId 公司ID
//     * @param supplierId 供应商ID
//     * @param materialId 材料ID
//     * @param weightType 过磅类型 1原材2辅材3商砼退料4砼过磅5登记皮重6原材出售过磅0其它过磅
//     * @param isPrint 是否打印
//     * @param isDisplay 是否显示
//     * @param isBill 是否结算
//     * @param startTime
//     * @param endTime
//     * @param offset
//     * @param limit
//     * @param searchType 0 已完成过磅， 1 未完成过磅
//     * @param carType 车辆类型(类型  1是搅拌车,2是材料车,3是外运车,4是水稳层,5其他,6内转车
     * @param isCloud 是否是云端 0 云端 1本地
     * @return
     */
    public IPage findPage(MainMaterialWeightVO materialWeight,
                          Integer isCloud, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        QueryWrapper<MainMaterialWeight> query = initFullParam(materialWeight.getSearchVal(), materialWeight.getOrgId(),
                materialWeight.getSupplierId(), materialWeight.getMaterialId(),
                materialWeight.getWeightType(), materialWeight.getIsPrint(), materialWeight.getIsDisplay(),
                materialWeight.getIsBill(), materialWeight.getStartTime(), materialWeight.getEndTime(),
                materialWeight.getStorageId(), materialWeight.getStatus(), materialWeight.getSearchType(),
                materialWeight.getCarType(), materialWeight.getIsCheck(), materialWeight.getIsStore(), 0, materialWeight.getDbCode());
        IPage<MainMaterialWeight> iPage = null;
        if (!StringUtils.isNull(materialWeight.getMaterialType()))
            query.inSql("a.material_id", "select id from oa_material " +
                    " where status = 0 and type = " + materialWeight.getMaterialType());
        if (!StringUtils.isNull(materialWeight.getBreedType()))
            query.inSql("a.material_id", "select id from oa_material " +
                    " where status = 0 and breed_type = " + materialWeight.getBreedType());
        if (isCloud == null || isCloud == 1) {
            iPage = materialWeightDao.findWeightPage(new Page<>((offset + limit) /limit, limit), query);
        } else {
            iPage = materialWeightDao.findCloudWeightPage(new Page<>((offset + limit) /limit, limit), query, materialWeight.getDbCode());
        }
        /**分页插件**/
        if (!StringUtils.isNull(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }
    public IPage findSupplierBillPage(MainMaterialWeightVO materialWeightVO, Integer isCloud,
                               Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        QueryWrapper<MainMaterialWeight> query = new QueryWrapper<>();
        query.eq("a.status", 0);
        query.eq("a.is_bill", 0);
        if (!StringUtils.isNull(materialWeightVO.getSupplierId()))
            query.eq("a.supplier_id", materialWeightVO.getSupplierId());
        if (!StringUtils.isNull(materialWeightVO.getMaterialId()))
            query.eq("a.material_id", materialWeightVO.getMaterialId());
        if (!StringUtils.isNull(materialWeightVO.getStartTime()))
            query.ge("a.out_time", materialWeightVO.getStartTime());
        if (!StringUtils.isNull(materialWeightVO.getEndTime()))
            query.lt("a.out_time", materialWeightVO.getEndTime());
        query.isNotNull("a.out_time");
        if (!StringUtils.isNull(materialWeightVO.getWeightType()))
            query.eq("a.weight_type", materialWeightVO.getWeightType());
        if (!StringUtils.isNull(materialWeightVO.getCarType()))
            query.eq("a.car_type", materialWeightVO.getCarType());
        if (!StringUtils.isNull(materialWeightVO.getContractType())) {
            if (materialWeightVO.getContractType() == MaterialContractTypeEnum.YSC.getCode() || materialWeightVO.getContractType() == MaterialContractTypeEnum.YSC.getCode()) {
                query.in("a.car_no", materialWeightVO.getCarNos());
            }
        }
        query.orderByAsc("a.out_time");
        IPage<MainMaterialWeight> iPage = materialWeightDao.findCloudWeightPage(new Page<>((offset + limit) /limit, limit), query, materialWeightVO.getDbCode());
        /**分页插件**/
        if (!StringUtils.isNull(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }
    /**
     * 根据仓位统计进料数据
     * @return
     */
    public List<MainMaterialWeightVo> findStorageWeight(String dbCode, String searchVal, Long supplierId, Long materialId,
              Long storageId, Integer breedType, Integer storageType, String startTime, String endTime) {
        if (StringUtils.isNull(dbCode))
            return null;
        List<MainMaterialWeightVo> weightVoList = materialWeightDao.findStorageWeight(dbCode, searchVal, supplierId,
                materialId, storageId, breedType, storageType, startTime, endTime);
        if (weightVoList == null || weightVoList.size() == 0)
            return null;
        return weightVoList;
    }

    /**
     * 查询云端统计数据
     * @param materialWeight
     * @return
     */
    public MainMaterialWeightVO findCloudTotalWeightPage(MainMaterialWeightVO materialWeight) {
        String dbCode = "";
        if (!StringUtils.isNull(materialWeight.getDbCode())) {
            dbCode = materialWeight.getDbCode();
        } else {
            DataSourceInfo ds = dsDao.queryDSByOriginIdV1(materialWeight.getOrgId(), DataBaseEnum.MYSQL.getCode());
            if (ds == null)
                return null;
            dbCode = ds.getCode();
        }
        QueryWrapper<MainMaterialWeight> query = initFullParam(materialWeight.getSearchVal(), materialWeight.getOrgId(),
                materialWeight.getSupplierId(), materialWeight.getMaterialId(),
                materialWeight.getWeightType(), materialWeight.getIsPrint(), materialWeight.getIsDisplay(),
                materialWeight.getIsBill(), materialWeight.getStartTime(), materialWeight.getEndTime(),
                materialWeight.getStorageId(), materialWeight.getStatus(), materialWeight.getSearchType(),
                materialWeight.getCarType(), materialWeight.getIsCheck(), materialWeight.getIsStore(), 1,dbCode);
        if (!StringUtils.isNull(materialWeight.getMaterialType()))
            query.inSql("a.material_id", "select id from oa_material " +
                    " where status = 0 and type = " + materialWeight.getMaterialType());
        if (!StringUtils.isNull(materialWeight.getBreedType()))
            query.inSql("a.material_id", "select id from oa_material " +
                    " where status = 0 and breed_type = " + materialWeight.getBreedType());
        return materialWeightDao.findCloudTotalWeightPage(query, dbCode);
    }

    /**
     * 保存过磅信息
     * @param materialWeight
     * @return
     */
    public RestResultDto save(MainMaterialWeight materialWeight) {
        if (materialWeight == null)
            return RestResultDto.fail("参数错误");
        if (materialWeight.getOrgId() == null)
            return RestResultDto.fail("公司信息为空");
        SysOrigin org = originDao.selectById(materialWeight.getOrgId());
        if (org == null || org.getStatus() == 1)
            return RestResultDto.fail("公司不存在或已被禁用");
        if (StringUtils.isNull(materialWeight.getIsAuto()))
            materialWeight.setIsAuto(1);
        if (!StringUtils.isNull(materialWeight.getIsCheck()) && materialWeight.getIsCheck() == 1)
            materialWeight.setChecker(materialWeight.getCreator());
        String phone = "123456";
        if (!StringUtils.isNull(materialWeight.getPhone())) {
            if (!StringUtils.validatorPhone(materialWeight.getPhone()))
                return RestResultDto.fail("电话号码格式错误");
            QueryWrapper<PlatformUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 0);
            queryWrapper.eq("phone", materialWeight.getPhone());
            queryWrapper.orderByDesc("id");
            List<PlatformUser> userList = platformUserDao.selectList(queryWrapper);
            if (userList != null && userList.size() > 0) {
                materialWeight.setOpenid(userList.get(0).getOpenid());
            }
            phone = materialWeight.getPhone();
        }
        if(!StringUtils.isNull(materialWeight.getRealGross()))
            materialWeight.setRealGross(materialWeight.getGross());
        if(!StringUtils.isNull(materialWeight.getRealNetWeight()))
            materialWeight.setRealNetWeight(materialWeight.getRealNetWeight());
        if (!StringUtils.isNull(materialWeight.getInTime()) && !StringUtils.isNull(materialWeight.getOutTime())) {
            if (materialWeight.getInTime().getTime() >= materialWeight.getOutTime().getTime())
                return RestResultDto.fail("入场时间不能大于出场时间");
        }
        if (!StringUtils.validatorCarNo(materialWeight.getCarNo()))
            return RestResultDto.fail("车牌号格式错误");

        String orderId = OrderNoUtil.getOrderNo(org.getOriginName(), phone);
        materialWeight.setCode(orderId);
        materialWeight.setCreateTime(new Date());
        Integer code = materialWeightDao.insert(materialWeight);
        if (code > 0)
            return RestResultDto.success("保存成功", materialWeight);
        return RestResultDto.fail("保存失败");
    }

    /**
     * 修改过磅信息
     * @param materialWeight
     * @return
     */
    public RestResultDto update(MainMaterialWeight materialWeight) {
        if (materialWeight == null || StringUtils.isNull(materialWeight.getId()))
            return RestResultDto.fail("参数错误");
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(materialWeight.getOrgId(),DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus() == 1)
            throw new MessageCenterException("数据源不存在或已被禁用");
        MainMaterialWeightVO oldWeight = materialWeightDao.selectByIdV1(materialWeight.getId(), ds.getCode());
        if (oldWeight == null || oldWeight.getStatus() == 1)
            return RestResultDto.fail("修改数据不存在或已被禁用");

        List<String> keyList = new ArrayList<>();
        List<Object> objList = new ArrayList<>();
        if (!StringUtils.isNull(materialWeight.getGross()) && !StringUtils.isNull(oldWeight.getGross())
        && !oldWeight.getGross().equals(materialWeight.getGross())) {
            oldWeight.setGross(materialWeight.getGross());
            keyList.add("gross");
            objList.add(materialWeight.getGross());
        }
        if (!StringUtils.isNull(materialWeight.getSupplierGross()) && !StringUtils.isNull(oldWeight.getSupplierGross())
                && !oldWeight.getSupplierGross().equals(materialWeight.getSupplierGross())) {
            oldWeight.setSupplierGross(materialWeight.getSupplierGross());
            keyList.add("supplierGross");
            objList.add(materialWeight.getSupplierGross());
        }
        if (!StringUtils.isNull(materialWeight.getTare()) && !StringUtils.isNull(oldWeight.getTare())
                && !oldWeight.getTare().equals(materialWeight.getTare())) {
            oldWeight.setTare(materialWeight.getTare());
            keyList.add("tare");
            objList.add(materialWeight.getTare());
        }
        if (!StringUtils.isNull(materialWeight.getSupplierTare()) && !StringUtils.isNull(oldWeight.getSupplierTare())
                && !oldWeight.getSupplierTare().equals(materialWeight.getSupplierTare())) {
            oldWeight.setSupplierTare(materialWeight.getSupplierTare());
            keyList.add("supplierTare");
            objList.add(materialWeight.getSupplierTare());
        }
        if (!StringUtils.isNull(materialWeight.getNetWeight()) && !StringUtils.isNull(oldWeight.getNetWeight())
                && !oldWeight.getNetWeight().equals(materialWeight.getNetWeight())) {
            oldWeight.setNetWeight(materialWeight.getNetWeight());
            keyList.add("netWeight");
            objList.add(materialWeight.getNetWeight());
        }
        if (!StringUtils.isNull(materialWeight.getSupplierNetWeight()) && !StringUtils.isNull(oldWeight.getSupplierNetWeight())
                && !oldWeight.getSupplierNetWeight().equals(materialWeight.getSupplierNetWeight())) {
            oldWeight.setSupplierNetWeight(materialWeight.getSupplierNetWeight());
            keyList.add("supplierNetWeight");
            objList.add(materialWeight.getSupplierNetWeight());
        }
        if (!StringUtils.isNull(materialWeight.getDriver()) && !StringUtils.isNull(oldWeight.getDriver())
                && !oldWeight.getDriver().equals(materialWeight.getDriver())) {
            oldWeight.setDriver(materialWeight.getDriver());
            keyList.add("driver");
            objList.add(materialWeight.getDriver());
        }
        if (!StringUtils.isNull(materialWeight.getPhone()) && !StringUtils.isNull(oldWeight.getPhone())
                && !oldWeight.getPhone().equals(materialWeight.getPhone())) {
            oldWeight.setPhone(materialWeight.getPhone());
            keyList.add("phone");
            objList.add(materialWeight.getPhone());
        }
        if (!StringUtils.isNull(materialWeight.getPrintTime()) && !StringUtils.isNull(oldWeight.getPrintTime())
                && !oldWeight.getPrintTime().equals(materialWeight.getPrintTime())) {
            oldWeight.setPrintTime(materialWeight.getPrintTime());
            keyList.add("printTime");
            objList.add(DateUtil.convertString(materialWeight.getPrintTime()));
        }
        if (!StringUtils.isNull(materialWeight.getStorageId()) && !StringUtils.isNull(oldWeight.getStorageId())
                && !oldWeight.getStorageId().equals(materialWeight.getStorageId())) {
            oldWeight.setStorageId(materialWeight.getStorageId());
            keyList.add("storageId");
            objList.add(materialWeight.getStorageId());
        }
        if (!StringUtils.isNull(materialWeight.getInTime()) && !StringUtils.isNull(oldWeight.getInTime())
                && !oldWeight.getInTime().equals(materialWeight.getInTime())) {
            oldWeight.setInTime(materialWeight.getInTime());
            keyList.add("inTime");
            objList.add(DateUtil.convertString(materialWeight.getInTime()));
        }
        if (!StringUtils.isNull(materialWeight.getOutTime()) && !StringUtils.isNull(oldWeight.getOutTime())
                && !oldWeight.getOutTime().equals(materialWeight.getOutTime())) {
            oldWeight.setOutTime(materialWeight.getOutTime());
            keyList.add("outTime");
            objList.add(DateUtil.convertString(materialWeight.getOutTime()));
        }
        if (!StringUtils.isNull(materialWeight.getIsPrint()) && !StringUtils.isNull(oldWeight.getIsPrint())
                && !oldWeight.getIsPrint().equals(materialWeight.getIsPrint())) {
            oldWeight.setIsPrint(materialWeight.getIsPrint());
            keyList.add("isPrint");
            objList.add(materialWeight.getIsPrint());
        }
        if (!StringUtils.isNull(materialWeight.getIsBill()) && !StringUtils.isNull(oldWeight.getIsBill())
                && !oldWeight.getIsBill().equals(materialWeight.getIsBill())) {
            oldWeight.setIsBill(materialWeight.getIsBill());
            keyList.add("isBill");
            objList.add(materialWeight.getIsBill());
        }
        if (!StringUtils.isNull(materialWeight.getUpdator()) && !StringUtils.isNull(oldWeight.getUpdator())
                && !oldWeight.getUpdator().equals(materialWeight.getUpdator())) {
            oldWeight.setUpdator(materialWeight.getUpdator());
            keyList.add("updator");
            objList.add(materialWeight.getUpdator());
        }
        if (!StringUtils.isNull(materialWeight.getRemark()) && !StringUtils.isNull(oldWeight.getRemark())
                && !oldWeight.getRemark().equals(materialWeight.getRemark())) {
            oldWeight.setRemark(materialWeight.getRemark());
            keyList.add("remark");
            objList.add(materialWeight.getRemark());
        }
        if (!StringUtils.isNull(materialWeight.getMaterialId()) && !StringUtils.isNull(oldWeight.getMaterialId())
                && !oldWeight.getMaterialId().equals(materialWeight.getMaterialId())) {
            oldWeight.setMaterialId(materialWeight.getMaterialId());
            keyList.add("materialId");
            objList.add(materialWeight.getMaterialId());
        }
        if (!StringUtils.isNull(materialWeight.getMaterial()) && !StringUtils.isNull(oldWeight.getMaterial())
                && !oldWeight.getMaterial().equals(materialWeight.getMaterial())) {
            oldWeight.setMaterial(materialWeight.getMaterial());
            keyList.add("material");
            objList.add(materialWeight.getMaterial());
        }
        Date nowDate = new Date();
        oldWeight.setUpdateTime(nowDate);
        Integer code = materialWeightDao.updateById(oldWeight);
        if (code > 0) {
            try {
                BusinessLog businessLog = new BusinessLog(oldWeight.getId(), oldWeight.getCode(),
                        BusinessTypeEnum.MATERIAL.getCode(), BusinessLog.convertJsonV1(keyList, objList));
                businessLog.setStatus(0);
                businessLog.setCreator(oldWeight.getUpdator());
                businessLog.setCreateTime(nowDate);
                businessLogDao.insert(businessLog);
            } catch (Exception e) {

            }
            return RestResultDto.success("更新成功");
        }
        return RestResultDto.fail("更新失败");
    }


    /**
     * 禁用/启用
     * @param id
     * @param status
     * @param remark
     * @param creator
     * @return
     */
    public RestResultDto updateStatus(Long id, Integer status, String remark, String creator) {
        if (StringUtils.isAllParamNull(id, status))
            return RestResultDto.fail("参数错误");
        MainMaterialWeight materialWeight = materialWeightDao.selectById(id);
        if (materialWeight == null)
            return RestResultDto.fail("过磅信息不存在");
        materialWeight.setStatus(status);
        if (!StringUtils.isNull(remark))
            materialWeight.setRemark(remark);
        if (!StringUtils.isNull(creator))
            materialWeight.setUpdator(creator);
        materialWeight.setUpdateTime(new Date());
        Integer code = materialWeightDao.updateById(materialWeight);
        if (code > 0)
            return RestResultDto.success("更新成功");
        return RestResultDto.fail("更新失败");
    }

    /**
     * 设置仓位信息
     * @param id
     * @param storageId 仓位ID
     * @param creator
     * @param remark
     * @return
     */
    public RestResultDto setStorage(Long id, Long storageId, String creator, String remark) {
        if (StringUtils.isAllParamNull(id, storageId))
            return RestResultDto.fail("参数错误");
        MainMaterialWeight materialWeight = materialWeightDao.selectById(id);
        if (materialWeight == null || materialWeight.getStatus() == 1)
            return RestResultDto.fail("过磅信息不存在或已被禁用");
        if (!StringUtils.isNull(remark))
            materialWeight.setRemark(remark);
        if (!StringUtils.isNull(creator))
            materialWeight.setUpdator(creator);
        materialWeight.setStorageId(storageId);
        materialWeight.setUpdateTime(new Date());
        Integer code = materialWeightDao.updateById(materialWeight);
        if (code > 0)
            return RestResultDto.success("更新成功");
        return RestResultDto.fail("更新失败");
    }

    /**
     * 设置扣重
     * @param id
     * @param hiddenWeight 暗扣重量
     * @param brightWeight 明扣重量
     * @param creator
     * @param remark
     * @return
     */
    public RestResultDto setWeight(Long id, Double hiddenWeight, Double brightWeight, String creator, String remark) {
        if (StringUtils.isNull(id))
            return RestResultDto.fail("参数错误");
        if (StringUtils.isNull(hiddenWeight) && StringUtils.isNull(brightWeight))
            return RestResultDto.fail("参数错误");
        MainMaterialWeight materialWeight = materialWeightDao.selectById(id);
        if (materialWeight == null || materialWeight.getStatus() == 1)
            return RestResultDto.fail("过磅信息不存在或已被禁用");
        if (!StringUtils.isNull(remark))
            materialWeight.setRemark(remark);
        if (!StringUtils.isNull(creator))
            materialWeight.setUpdator(creator);
        Double weight = hiddenWeight + brightWeight;
        materialWeight.setHiddenWeight(hiddenWeight);
        materialWeight.setBrightWeight(brightWeight);
        materialWeight.setDeductWeight(weight);
        //变更毛重、净重
        materialWeight.setGross(StringUtils.formatDouble(materialWeight.getRealGross() - weight, 2));
        materialWeight.setNetWeight(StringUtils.formatDouble(materialWeight.getRealNetWeight() - weight, 2));
        materialWeight.setUpdateTime(new Date());
        Integer code = materialWeightDao.updateById(materialWeight);
        if (code > 0)
            return RestResultDto.success("更新成功");
        return RestResultDto.fail("更新失败");
    }

    /**
     * 设置显示
     * @param ids
     * @param startTime
     * @param endTime
     * @param creator
     * @param displayRate 显示扣除比例
     * @param remark
     * @return
     */
    public RestResultDto setDisplayRate(String ids, String startTime, String endTime, Double displayRate,
                                 String creator, String remark) {
        if (!StringUtils.isNull(ids)) {

        } else if (!StringUtils.isNull(startTime) && !StringUtils.isNull(endTime)) {

        } else {
            return RestResultDto.fail("设置类型错误");
        }
        return null;
    }

    /**
     * 审核过磅单
     * @param ids
     * @param creator
     * @param remark
     * @param type 0 材料统计审核 1 财务审核
     * @return
     */
    public RestResultDto checkWeight(Long orgId, String ids, String creator, String remark, Integer type) {
        if (StringUtils.isAllParamNull(ids, type))
            return RestResultDto.fail("参数错误");
        String[] id = ids.split(",");
        if (id == null || id.length == 0)
            return RestResultDto.fail("未获取到审核磅单");
//        UpdateWrapper<MainMaterialWeight> updateWrapper = new UpdateWrapper<>();
//        updateWrapper.eq("status", 0);
//        updateWrapper.in("id", id);
//        if (type == 0) {
//            updateWrapper.set("is_check", 1);
//            updateWrapper.set("checker", creator);
//            updateWrapper.set("updator", creator);
//            updateWrapper.set("update_time", new Date());
//            Integer code = materialWeightDao.update(new MainMaterialWeight(), updateWrapper);
//            if (code > 0)
//                return RestResultDto.success("审核成功");
//            return RestResultDto.fail("审核失败");
//        } else if (type == 1) {
//            updateWrapper.set("is_finance", 1);
//            updateWrapper.set("finance", creator);
//            updateWrapper.set("updator", creator);
//            updateWrapper.set("update_time", new Date());
//            Integer code = materialWeightDao.update(new MainMaterialWeight(), updateWrapper);
//            if (code > 0)
//                return RestResultDto.success("审核成功");
//            return RestResultDto.fail("审核失败");
//        } else {
//            return RestResultDto.fail("审核类型错误");
//        }
        Date nowDate = new Date();
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(orgId,DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus().intValue() == 1)
            throw new MessageCenterException("审核过磅单数据源不存在或已被删除");
        String tempIds = "";
        for (int i = 0; i < id.length; i++) {
            tempIds += id[i] + ",";
        }
        tempIds = tempIds.substring(0, tempIds.length() - 1);
        String sql = "update " + ds.getCode() + ".main_material_weight set is_check=0,checker='" + creator
                + "',updator='" + creator + "',update_time='" + DateUtil.convertString(nowDate) + "' " +
                " where status = 0 and is_check = 1 and car_type = 2 and weight_type = 1 and id in (" + tempIds + ")";
        if (type == 1) {
            sql = "update " + ds.getCode() + ".main_material_weight set is_finance=1,finance='" + creator
                    + "',updator='" + creator + "',update_time='" + DateUtil.convertString(nowDate) + "' " +
                    " where status = 0 and is_finance = 1 and car_type = 2 and weight_type = 1 and id in (" + tempIds + ")";
        }
        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
        Integer code = jdbcTemplate.update(sql);
        if (code > 0) {
            code = materialWeightDao.updateCloudSql(sql);
//            if (code < 1)
//                throw new MessageCenterException("更新云端数据异常");

            return RestResultDto.success("审核成功~！");
        }
        return RestResultDto.fail("暂无更新项~！");
    }
    
    /**
     * 汽车过磅记录
     * @param dto
     * @return
     */
    public IPage<MainMaterialWeightVO> pageData(MaterialWeightQueryDTO dto){
        PageHelper.offsetPage(dto.getOffsetSize(), dto.getLimit());
        Page<MainMaterialWeight> page = new Page<>(dto.getCurrSize(), dto.getLimit());
        //3商砼退料 4砼过磅 5登记皮重
        if(ObjectUtil.isEmpty(dto.getWeightType())){
            dto.setWeightTypeList(Arrays.asList(3,4,5));
        }
        IPage<MainMaterialWeightVO> iPage = materialWeightDao.pageData(page, dto);
        /**分页插件**/
        if (ObjectUtil.isNotEmpty(iPage)) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal())) iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }

    /**
     * 根据订单信息，获取图片
     * @param orgId
     * @param code
     * @return
     */
    public List<WeightPicture> loadImageList(Long orgId, String code) {
        if (StringUtils.isAllParamNull(orgId, code))
            throw new MessageCenterException("获取过磅单图片列表参数错误");
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(orgId,DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus().intValue() == 1)
            throw new MessageCenterException("获取过磅单图片数据源不存在或已被删除");
        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
        String sql = "select id,img_url imgUrl,type, code from weight_picture " +
                " where status = 0 and code = '" + code + "' order by id ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (list == null || list.size() == 0)
            return null;
        List<WeightPicture> weightPictureList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            WeightPicture picture = new WeightPicture();
            picture.setId(StringUtils.convertLong(map.get("id")));
            picture.setImgUrl(StringUtils.convertString(map.get("imgUrl")));
            picture.setType(StringUtils.convertInteger(map.get("type")));
            picture.setCode(StringUtils.convertString(map.get("code")));
            weightPictureList.add(picture);
        }
        return weightPictureList;
    }

    /**
     * 加载过磅照片
     * @param orgId
     * @param id
     * @return
     */
    public byte[] loadMaterialImage(Long orgId, Long id) {
        if (StringUtils.isAllParamNull(orgId, id))
            throw new MessageCenterException("获取过磅单图片参数错误");
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(orgId,DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus().intValue() == 1)
            throw new MessageCenterException("获取过磅单图片数据源不存在或已被删除");
        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
        String sql = "select id,code,img_size imgSize,img_url imgUrl,picture_bit pictureBit,type from weight_picture " +
                " where status = 0 and id = " + id + " order by id ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (list == null || list.size() == 0)
            return null;
        byte[] img = (byte[]) list.get(0).get("pictureBit");
        return img;
    }

    /**
     * 统计查询各供应商进料数据
     * @param orgId
     * @param supplierId
     * @param materialId
     * @param type 0地材 1非地材
     * @param searchVal
     * @param startTime
     * @param endTime
     * @return
     */
    public List<MainMaterialWeightVO> findCloudTotalSupplier(Long orgId, Long supplierId, Long materialId,
                                                      Integer type, String searchVal, String startTime, String endTime) {
        if (StringUtils.isNull(orgId))
            return null;
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(orgId,DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus().intValue() == 1)
            return null;
        String searchType = null;
        if (!StringUtils.isNull(type)) {
            if (type == 1)
                searchType = "2,5,6";
            else if (type == 0)
                searchType = "3,4,9";
            else
                searchType = null;
        }
        List<MainMaterialWeightVO> weightList = materialWeightDao.findCloudTotalSupplier(ds.getCode(),orgId,
                supplierId, materialId, searchType, searchVal, startTime, endTime);
        if (weightList == null || weightList.size() == 0)
            return null;
        return weightList;
    }

    private QueryWrapper<MainMaterialWeight> initFullParam(String searchVal, Long orgId, Long supplierId, Long materialId, Integer weightType,
                                   Integer isPrint, Integer isDisplay, Integer isBill, String startTime, String endTime,
                                   Long storageId, Integer status, Integer searchType, Integer carType, Integer isCheck,
                                   Integer isStore, Integer isGroup, String dbCode) {
        QueryWrapper<MainMaterialWeight> query = new QueryWrapper<>();
        if (StringUtils.isNull(status))
            status = 0;
        if (StringUtils.isNull(searchType))
            searchType = 0;
//        if (StringUtils.isNull(isBill))
//            isBill = 0;
        if (!StringUtils.isNull(orgId))
            query.eq("a.org_id", orgId);
        if (!StringUtils.isNull(supplierId))
            query.eq("a.supplier_id", supplierId);
        if (!StringUtils.isNull(materialId))
            query.eq("a.material_id", materialId);
        if (!StringUtils.isNull(weightType))
            query.eq("a.weight_type", weightType);
        if (!StringUtils.isNull(isPrint))
            query.eq("a.is_print", isPrint);
        if (!StringUtils.isNull(isDisplay))
            query.eq("a.is_display", isDisplay);
        if (!StringUtils.isNull(isBill))
            query.eq("a.is_bill", isBill);
        if (!StringUtils.isNull(storageId))
            query.eq("a.storage_id", storageId);
        if (!StringUtils.isNull(carType))
            query.eq("a.car_type", carType);
        if (!StringUtils.isNull(isCheck))
            query.eq("a.is_check", isCheck);
        if (!StringUtils.isNull(isStore))
            query.eq("a.is_store", isStore);
        if (StringUtils.isNull(searchType)) {
            //未选择类型
            if (!StringUtils.isNull(startTime))
                query.ge("a.create_time", startTime);
            if (!StringUtils.isNull(endTime))
                query.lt("a.create_time", endTime);
        } else {
            if (searchType == 0) {
                if (!StringUtils.isNull(startTime))
                    query.ge("a.out_time", startTime);
                if (!StringUtils.isNull(endTime))
                    query.lt("a.out_time", endTime);
                query.isNotNull("a.out_time");
            } else if (searchType == 1) {
                if (!StringUtils.isNull(startTime))
                    query.ge("a.in_time", startTime);
                if (!StringUtils.isNull(endTime))
                    query.lt("a.in_time", endTime);
                query.isNotNull("a.in_time");
            }
        }

        if (!StringUtils.isNull(storageId))
            query.eq("a.storage_id", storageId);
        if (!StringUtils.isNull(status))
            query.eq("a.status", status);
        if (!StringUtils.isNull(searchVal)) {
            String sql = "select id from sys_storage where status = 0 and name like '%" + searchVal + "%'";
            if (!StringUtils.isNull(dbCode))
                sql = "select id from " + dbCode +".sys_storage where status = 0 and name like '%" + searchVal + "%'";
            String finalSql = sql;
            query.and(orderWrapper -> orderWrapper.like("a.code", searchVal).or()
                    .like("a.car_no", searchVal).or().like("a.remark", searchVal)
                    .or().like("a.driver", searchVal).or().like("a.phone", searchVal)
                    .or().like("a.material", searchVal).or().like("a.supplier", searchVal)
                    .or().inSql("a.storage_id", finalSql));
        }
        if (isGroup == 0)
            query.groupBy("a.id");
        if (searchType == 0)
            query.orderByAsc("a.out_time", "a.create_time");
        else if (searchType == 1)//导出排序
            query.orderByDesc("a.in_time");
        return query;
    }
}
